<?php

namespace app\admin\controller\routine;



use app\admin\service\SiteSiteService;
use app\common\controller\Backend;
use app\common\dict\TaskStatusDict;
use app\common\exception\AdminApiException;
use app\common\service\QueueTaskLogService;
use Throwable;

class QueueTasks extends Backend
{


    protected array $withJoinTable = ['logs','site'];


    protected bool $limitSiteId = false;



    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\common\model\QueueTasks();
    }



    /**
     * 查看
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark()
        ]);
    }


    /**
     * 查看详情
     * @return void
     */
    public function detail()
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $row->appendData([
            'logs' => (new QueueTaskLogService())->list(['task_id' => $id],['id' => 'dec'],"*",0, 100),
            'site' => (new SiteSiteService())->info(['site_id' => $row->site_id])
        ]);

        $this->success('',$row);

    }


    /**
     * 重新发布
     * @return void
     */
    public function push()
    {
        $ids  = $this->request->param('ids', null);
        if(!$ids) $this->error('参数错误');
        $list = $this->model->where('id', 'in', $ids)->select();
        if (!$list) {
            $this->error(__('Record not found'));
        }


        $ret = false;
        $this->model->startTrans();
        try {

            foreach ($list as $row){

                if(!in_array($row->status, [TaskStatusDict::TIMEOUT, TaskStatusDict::FAILURE])){
                    throw new AdminApiException('当前任务状态不可执行！');
                }

                if(!$row->class && !class_exists($row->class)){
                    throw new AdminApiException('当前任务的类名不可用！');
                }

                //调用$row->class类名中的静态方法republish()
                $class = new $row->class();
                if(method_exists($class, 'republish')){
                    $row->status = TaskStatusDict::INIT;
                    $ret += $row->save();
                    $class::republish($row->id);
                }else{
                    $this->error('当前任务的类名不可用！');
                }

            }

            $this->model->commit();
        }catch (Throwable $e){
            $this->model->rollback();
            $this->error($e->getMessage());
        }

        if($ret){
            $this->success('重新发布成功！');
        }else{
            $this->error('重新发布失败！');
        }

    }



}